﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.IO;
using System.Xml.Serialization;

namespace ChgDoc.Render
{
	public abstract class ResponseRenderParameters<T> 
	{
		public string Serialize()
		{
			XmlSerializer serializer = new XmlSerializer( typeof( T ) );
			using (StringWriter writer = new StringWriter())
			{
				serializer.Serialize( writer, this );
				return writer.GetStringBuilder().ToString();
			}
		}

		public static string Serialize( T t )
		{
			XmlSerializer serializer = new XmlSerializer( typeof( T ) );
			using (StringWriter writer = new StringWriter())
			{
				serializer.Serialize( writer, t );
				return writer.GetStringBuilder().ToString();
			}
		}
		
		public static T Deserialize( string xml )
		{
			if (string.IsNullOrEmpty( xml ))
				return Activator.CreateInstance<T>();

			try
			{
				XmlSerializer serializer = new XmlSerializer( typeof( T ) );
				return (T)serializer.Deserialize( new StringReader( xml ) );
			}
			catch (Exception ex)
			{
				return Activator.CreateInstance<T>();
                Config.Log.Error("** RenderParameters Deserialize type: " + typeof(T), ex);
			}
		}
	}
}